//
//  OAuthViewController.swift
//  WeoboWithSteveLi
//
//  Created by SteveLi on 2017/9/30.
//  Copyright © 2017年 李军桦. All rights reserved.
//

import UIKit
import SVProgressHUD
class OAuthViewController: UIViewController {
    lazy var webView = UIWebView()
    //设置界面
    override func loadView() {
        view = webView
        //设置代理
        webView.delegate = self
        
        //设置导航栏
        title = "登录新浪微博"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .plain, target: self, action: #selector(close))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .plain, target: self, action: #selector(autoFile))
      
    }
    //MARK: -监听方法
    func close() {
        SVProgressHUD.dismiss()
        dismiss(animated: true, completion: nil)
    }
    /// 自动填充用户名和密码  -web 注入(以代码的方式向web页面添加内容)
    func autoFile(){
        let js = "document.getElementById('userId').value = '17781847727';" + "document.getElementById('passwd').value = '978677728a'"
        //让webView执行js
        webView.stringByEvaluatingJavaScript(from: js)
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        //在开发中，如果用纯代码开发，视图最好指定背景颜色，如果为nil，会影响渲染效率
        view.backgroundColor = UIColor.white
        //加载页面
        self.webView.loadRequest(NSURLRequest(url: NetworkTools.sharedTools.oauthURL as URL) as URLRequest)
    }
}
extension OAuthViewController:UIWebViewDelegate{
    /// 将要加载请求的代理方法
    ///
    /// - parameter webView:        webView
    /// - parameter request:        将要加载的请求，返回false不加载，返回true继续加载
    /// - parameter navigationType: navigationType,页面跳转的方式
    ///
    /// - returns: 返回false不加载，返回true继续加载
    /// 如果 IOS 的代理方法中返回bool ,通常返回 true 很正常，返回 false 不能正常工作
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //目标：如果是百度，就不加载
        //1.判断访问的主机是否是www.baidu.com
        guard  let url = request.url, url.host == "www.baidu.com" else {
            return true
        }
        //2.从百度地址的url中 提取 code= 是否存在
        guard let query = url.query, query.hasPrefix("code")  else {
            print("取消授权")
            close()
            return false
        }
        //3.从query字符串中提取‘code=’后面的授权码
        let code = query.substring(from: "code=".endIndex)
        print("授权码是"+code)
        UserAccountViewModel.sharedUserAccount.loadAccessToken(code: code) { (isScuessed) in
            //finished 的完整代码
            if !isScuessed {
                SVProgressHUD.showInfo(withStatus: "您的网络不给力")
                delay(0.5, callFunc: {
                    self.close()
                })
                print("失败了")
                return
            }
            print("成功了")
            //dismiss不会立即将控制器销毁
            self.dismiss(animated: false){
                //停止指示器
                SVProgressHUD.dismiss()
                //通知中心是同步到 --- 一旦发送通知，会先执行监听方法，直到结束后，才执行后续代码
                NotificationCenter.default.post(name: WBSwitchRootViewControllerNotification, object: "welcome")            
            }
        }
        return false
    }
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
}




